package org.example.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.example.Tools.MD5Util;
import org.example.dto.SelectUserRoleResultDto;
import org.example.entity.User;
import org.example.mapper.RoleMapper;
import org.example.mapper.UsersMapper;
import org.example.service.IUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 
 * @since 2025-03-27
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, User> implements IUsersService {

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private RoleMapper roleMapper;
    @Override
    public User FindUser(User usr) {
        return usersMapper.FindUser(usr);
    }

    @Override
    public User FindUserByPhone(String phone) {
        return usersMapper.FindUserByPhone(phone);
    }


    @Override
    public List<SelectUserRoleResultDto> selectUserRole(String phone) {
        return usersMapper.selectUserRole(phone);
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone,s);
        User user = baseMapper.selectOne(wrapper);
        List<SelectUserRoleResultDto> roles =
                usersMapper.selectUserRole(user.getPhone());
        if(user==null){
            throw  new UsernameNotFoundException("用户不存在");
        }

//        UserDetails userdeatils= org.springframework.security.core.userdetails.User
//                .withUsername(user.getUserName())
//                .password(user.getLoginPassword())
//                .authorities("ROLE_ADMIN").build(); //没有权限所以写死
//
//        return userdeatils;

        List<GrantedAuthority> authorities = roles
                .stream()
                .map(role -> new SimpleGrantedAuthority(role.getRoleName())) // 添加ROLE_ 前缀
                .collect(Collectors.toList());
        UserDetails detail =
                org.springframework.security.core.userdetails.User.withUsername(user.getPhone())
                        .password(MD5Util.md5(user.getPassword()))
                        .authorities(authorities).build();
        return detail;
    }

    @Override
    public int setUserPhone(String phone, Integer id) {
        return usersMapper.setUserPhone(phone,id);
    }
}
